from django import forms
from django.core.validators import RegexValidator
from users.models import Users
from django_redis import get_redis_connection   # 缓存数据库
# 创建手机号的正则校验器
mobile_validator = RegexValidator(r'^1[3-9]\d{9}$', '手机号码格式不正确')


class CheckImgCodeForm(forms.Form):
    """check image code """
    mobile = forms.CharField(max_length=11, min_length=11, validators=[mobile_validator,],
                             error_messages={
                                 "min_length": "手机号长度有误",
                                 "max_length": "手机号长度有误",
                                 "required" : "手机号不能为空"})

    text = forms.CharField(max_length=4, min_length=4,
                           error_messages={"min_length": "图片验证码长度有误",
                                           "max_length": "图片验证码长度有误",
                                           "required": "图片验证码不能为空"})

    image_code_id = forms.UUIDField(error_messages={"required": "图片UUID不能为空"})

    def clean_mobile(self): # 指定字段进行验证方法的添加
        """校验手机号是否注册"""
        tel = self.cleaned_data.get('mobile')
        if Users.objects.filter(mobile=tel).count():
            raise forms.ValidationError('手机号码已经注册，请重新输入！')
        return tel

    def clean(self):    # 多个字段需要添加验证方法时使用
        cleaned_data = super().clean()
        mobile_num = cleaned_data.get('mobile')
        image_uuid = cleaned_data.get('image_code_id')
        image_text = cleaned_data.get('text')
        if mobile_num and image_uuid and image_text:
            # 检验图形验证码是否一致
            # 这个存在了redis里面
            redis_conn = get_redis_connection(alias='verify_code')
            img_code = redis_conn.get("img_{}".format(image_uuid))
            if not img_code:
                raise forms.ValidationError('图形验证码失效')
            if image_text.upper() != str(img_code, encoding='utf-8').upper():
                raise forms.ValidationError('图形验证码校验失败！')
            # 检验是否60秒以内发送过短信
            if redis_conn.get('sms_flag_{}'.format(mobile_num)):
                raise forms.ValidationError('获取短信验证码过于频繁！')

        return cleaned_data



